<template>
  <div class="page-content">
    <ElForm :model="queryForm" :inline="true">
      <!-- 第一行：基础筛选 -->
      <ElRow :gutter="16" style="margin-bottom: 16px">
        <ElCol :xs="24" :sm="8" :md="6" :lg="16">
          <ElSpace :size="1">
            <ElFormItem label="关键字搜索">
              <ElInput
                v-model="queryForm.keyword"
                placeholder="昵称/手机号/openid"
                clearable
                style="min-width: 200px"
              />
            </ElFormItem>
            <ElFormItem label="用户状态">
              <ElSelect
                v-model="queryForm.status"
                placeholder="请选择状态"
                clearable
                style="width: 100%; min-width: 150px"
              >
                <ElOption label="正常" value="active" />
                <ElOption label="已封禁" value="blocked" />
                <ElOption label="已删除" value="deleted" />
              </ElSelect>
            </ElFormItem>
            <ElFormItem label="用户角色">
              <ElSelect
                v-model="queryForm.role"
                placeholder="请选择角色"
                clearable
                style="width: 100%; min-width: 150px"
              >
                <ElOption label="普通用户" value="normal" />
                <ElOption label="VIP用户" value="vip" />
              </ElSelect>
            </ElFormItem>
          </ElSpace>
        </ElCol>

        <ElCol :xs="24" :sm="8" :md="12" :lg="8">
          <ElFormItem>
            <ElSpace :size="12">
              <ElButton type="primary" @click="handleSearch" v-ripple>搜索</ElButton>
              <ElButton @click="resetQuery" v-ripple>重置</ElButton>
            </ElSpace>
          </ElFormItem>
        </ElCol>
      </ElRow>
    </ElForm>

    <ArtTable
      :data="userList"
      :loading="loading"
      :total="pagination.total"
      v-model:current-page="pagination.page"
      v-model:page-size="pagination.size"
      :page-sizes="[10, 20, 50, 100]"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :show-pagination="true"
      :hide-on-single-page="false"
      index
    >
      <template #default>
        <ElTableColumn label="头像" prop="avatarUrl" width="80">
          <template #default="scope">
            <ElAvatar
              v-if="scope.row.avatarUrl"
              :src="scope.row.avatarUrl"
              :size="40"
              shape="circle"
            />
            <ElAvatar v-else :size="40" shape="circle">
              <ElIcon><User /></ElIcon>
            </ElAvatar>
          </template>
        </ElTableColumn>
        <ElTableColumn label="用户信息" min-width="200">
          <template #default="scope">
            <div class="user-info">
              <div class="nickname">{{ scope.row.nickName }}</div>
              <div class="phone">{{ scope.row.phone || '-' }}</div>
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn label="性别" prop="gender" width="80">
          <template #default="scope">
            {{ getGenderText(scope.row.gender) }}
          </template>
        </ElTableColumn>
        <ElTableColumn label="地区" min-width="150">
          <template #default="scope">
            {{ formatLocation(scope.row) }}
          </template>
        </ElTableColumn>
        <ElTableColumn label="角色" prop="role" width="100">
          <template #default="scope">
            <ElTag :type="getUserRoleTagType(scope.row.role)">
              {{ getUserRoleText(scope.row.role) }}
            </ElTag>
          </template>
        </ElTableColumn>
        <ElTableColumn label="状态" prop="status" width="100">
          <template #default="scope">
            <ElTag :type="getUserStatusTagType(scope.row.status)">
              {{ getUserStatusText(scope.row.status) }}
            </ElTag>
          </template>
        </ElTableColumn>
        <ElTableColumn label="VIP状态" min-width="150">
          <template #default="scope">
            <ElTag
              v-if="scope.row.role === 'vip'"
              :type="isVipValid(scope.row) ? 'warning' : 'info'"
              size="small"
            >
              {{ getVipStatusText(scope.row) }}
            </ElTag>
            <span v-else>-</span>
          </template>
        </ElTableColumn>
        <ElTableColumn label="注册时间" prop="createTime" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </ElTableColumn>
        <ElTableColumn label="最后登录" prop="lastLoginTime" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.lastLoginTime) }}
          </template>
        </ElTableColumn>
        <ElTableColumn fixed="right" label="操作" width="200">
          <template #default="scope">
            <ElButton type="primary" link @click="showDetailDialog(scope.row)">详情</ElButton>
            <ElButton
              v-if="scope.row.status === 'active'"
              type="warning"
              link
              @click="handleBlock(scope.row)"
            >
              封禁
            </ElButton>
            <ElButton
              v-if="scope.row.status === 'blocked'"
              type="success"
              link
              @click="handleUnblock(scope.row)"
            >
              解封
            </ElButton>
            <ElButton
              v-if="canSetVip(scope.row)"
              type="primary"
              link
              @click="showVipDialog(scope.row)"
            >
              设为VIP
            </ElButton>
            <ElButton
              v-if="canCancelVip(scope.row)"
              type="warning"
              link
              @click="handleCancelVip(scope.row)"
            >
              取消VIP
            </ElButton>
            <ElButton
              v-if="scope.row.status !== 'deleted'"
              type="danger"
              link
              @click="handleDelete(scope.row)"
            >
              删除
            </ElButton>
          </template>
        </ElTableColumn>
      </template>
    </ArtTable>

    <!-- 用户详情弹窗 -->
    <ElDialog v-model="detailDialogVisible" title="用户详情" width="800px" align-center>
      <div v-if="currentUser" class="user-detail">
        <ElDescriptions :column="2" border>
          <ElDescriptionsItem label="头像">
            <ElAvatar
              v-if="currentUser.avatarUrl"
              :src="currentUser.avatarUrl"
              :size="60"
              shape="circle"
            />
            <ElAvatar v-else :size="60" shape="circle">
              <ElIcon><User /></ElIcon>
            </ElAvatar>
          </ElDescriptionsItem>
          <ElDescriptionsItem label="昵称">
            {{ currentUser.nickName }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="OpenID">
            {{ currentUser.openid }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="手机号">
            {{ currentUser.phone || '-' }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="性别">
            {{ getGenderText(currentUser.gender) }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="地区">
            {{ formatLocation(currentUser) }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="用户角色">
            <ElTag :type="getUserRoleTagType(currentUser.role)">
              {{ getUserRoleText(currentUser.role) }}
            </ElTag>
          </ElDescriptionsItem>
          <ElDescriptionsItem label="用户状态">
            <ElTag :type="getUserStatusTagType(currentUser.status)">
              {{ getUserStatusText(currentUser.status) }}
            </ElTag>
          </ElDescriptionsItem>
          <ElDescriptionsItem label="注册时间">
            {{ formatDate(currentUser.createTime) }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="更新时间">
            {{ formatDate(currentUser.updateTime) }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="最后登录">
            {{ formatDate(currentUser.lastLoginTime) }}
          </ElDescriptionsItem>
        </ElDescriptions>

        <!-- VIP信息 -->
        <div class="mt-4" v-if="currentUser.vipInfo && currentUser.role === 'vip'">
          <ElDescriptions :column="2" border title="VIP信息">
            <ElDescriptionsItem label="VIP类型">
              {{ getVipTypeText(currentUser.vipInfo.type) }}
            </ElDescriptionsItem>
            <ElDescriptionsItem label="激活状态">
              <ElTag :type="currentUser.vipInfo.isActive ? 'success' : 'danger'">
                {{ currentUser.vipInfo.isActive ? '已激活' : '未激活' }}
              </ElTag>
            </ElDescriptionsItem>
            <ElDescriptionsItem label="激活时间">
              {{ formatDate(currentUser.vipInfo.activatedAt) }}
            </ElDescriptionsItem>
            <ElDescriptionsItem label="过期时间" v-if="currentUser.vipInfo.type !== 'lifetime'">
              {{ formatDate(currentUser.vipInfo.expiresAt) }}
            </ElDescriptionsItem>
            <ElDescriptionsItem label="关联订单">
              {{ currentUser.vipInfo.orderId }}
            </ElDescriptionsItem>
            <ElDescriptionsItem label="VIP状态">
              <ElTag :type="isVipValid(currentUser) ? 'success' : 'warning'">
                {{ getVipStatusText(currentUser) }}
              </ElTag>
            </ElDescriptionsItem>
          </ElDescriptions>
        </div>

        <!-- 地址信息 -->
        <div class="mt-4" v-if="currentUser.addresses?.length">
          <ElDescriptions :column="1" border title="地址列表">
            <ElDescriptionsItem label="收货地址">
              <ElTable :data="currentUser.addresses" size="small">
                <ElTableColumn label="收货人" prop="name" />
                <ElTableColumn label="手机号" prop="phone" />
                <ElTableColumn label="地址" min-width="200">
                  <template #default="scope">
                    {{ scope.row.province }}{{ scope.row.city }}{{ scope.row.district
                    }}{{ scope.row.detail }}
                  </template>
                </ElTableColumn>
                <ElTableColumn label="默认" prop="isDefault" width="80">
                  <template #default="scope">
                    <ElTag v-if="scope.row.isDefault" type="primary" size="small">默认</ElTag>
                  </template>
                </ElTableColumn>
                <ElTableColumn label="创建时间" prop="createTime" width="180">
                  <template #default="scope">
                    {{ formatDate(scope.row.createTime) }}
                  </template>
                </ElTableColumn>
              </ElTable>
            </ElDescriptionsItem>
          </ElDescriptions>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <ElButton @click="detailDialogVisible = false">关闭</ElButton>
        </div>
      </template>
    </ElDialog>

    <!-- 设置VIP弹窗 -->
    <ElDialog
      v-model="vipDialogVisible"
      title="设置VIP"
      width="500px"
      align-center
      :close-on-click-modal="false"
    >
      <ElForm ref="vipFormRef" :model="vipForm" :rules="vipRules" label-width="120px">
        <ElFormItem label="VIP类型" prop="type">
          <ElSelect v-model="vipForm.type" placeholder="请选择VIP类型" style="width: 100%">
            <ElOption label="月度会员" value="monthly" />
            <ElOption label="年度会员" value="yearly" />
            <ElOption label="终身会员" value="lifetime" />
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="关联订单" prop="orderId">
          <ElInput v-model="vipForm.orderId" placeholder="请输入关联订单ID" />
        </ElFormItem>
        <ElFormItem label="激活状态" prop="isActive">
          <ElSwitch v-model="vipForm.isActive" />
        </ElFormItem>
        <ElFormItem label="激活时间" prop="activatedAt">
          <ElDatePicker
            v-model="vipForm.activatedAt"
            type="datetime"
            placeholder="选择激活时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="X"
            style="width: 100%"
          />
        </ElFormItem>
        <ElFormItem
          label="过期时间"
          prop="expiresAt"
          v-if="vipForm.type && vipForm.type !== 'lifetime'"
        >
          <ElDatePicker
            v-model="vipForm.expiresAt"
            type="datetime"
            placeholder="选择过期时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="X"
            style="width: 100%"
          />
        </ElFormItem>
      </ElForm>
      <template #footer>
        <div class="dialog-footer">
          <ElButton @click="vipDialogVisible = false">取消</ElButton>
          <ElButton type="primary" @click="handleSetVip" :loading="submitLoading">确定</ElButton>
        </div>
      </template>
    </ElDialog>
  </div>
</template>

<script setup lang="ts">
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import { User } from '@element-plus/icons-vue'
  import {
    UserService,
    type User as UserType,
    type UserListParams,
    type UpdateVipParams,
    getUserStatusText,
    getUserStatusTagType,
    getUserRoleText,
    getUserRoleTagType,
    getGenderText,
    getVipTypeText,
    getVipStatusText,
    isVipValid,
    formatDate,
    canSetVip,
    canCancelVip
  } from '@/api/userApi'

  defineOptions({ name: 'UserManage' })

  // 响应式数据
  const loading = ref(false)
  const submitLoading = ref(false)
  const detailDialogVisible = ref(false)
  const vipDialogVisible = ref(false)
  const vipFormRef = ref<FormInstance>()
  const currentUser = ref<UserType | null>(null)

  // 查询表单
  const queryForm = reactive<UserListParams>({
    keyword: '',
    status: undefined,
    role: undefined
  })

  // 分页数据
  const pagination = reactive({
    page: 1,
    size: 10,
    total: 0
  })

  // 用户列表
  const userList = ref<UserType[]>([])

  // VIP表单数据
  const vipForm = reactive<UpdateVipParams>({
    type: 'monthly',
    activatedAt: Math.floor(Date.now() / 1000),
    expiresAt: null,
    orderId: '',
    isActive: true
  })

  // VIP表单验证规则
  const vipRules = reactive<FormRules>({
    type: [{ required: true, message: '请选择VIP类型', trigger: 'change' }],
    orderId: [
      { required: true, message: '请输入关联订单ID', trigger: 'blur' },
      { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
    ],
    activatedAt: [{ required: true, message: '请选择激活时间', trigger: 'change' }]
  })

  // 获取用户列表
  const getUserList = async () => {
    try {
      loading.value = true
      const params: UserListParams = {
        page: pagination.page,
        size: pagination.size,
        ...queryForm
      }
      const response = await UserService.getUserList(params)
      console.log('response', response)
      if (response.code === 200) {
        userList.value = response.data
        pagination.total = response.total
      } else {
        ElMessage.error(response.message)
      }
    } catch (error) {
      ElMessage.error('获取用户列表失败')
      console.error('获取用户列表失败:', error)
      userList.value = []
      pagination.total = 0
    } finally {
      loading.value = false
    }
  }

  // 搜索
  const handleSearch = () => {
    pagination.page = 1
    getUserList()
  }

  // 重置查询
  const resetQuery = () => {
    Object.assign(queryForm, {
      keyword: '',
      status: undefined,
      role: undefined
    })
    pagination.page = 1
    getUserList()
  }

  // 分页处理
  const handleSizeChange = (val: number) => {
    pagination.size = val
    pagination.page = 1
    getUserList()
  }

  const handleCurrentChange = (val: number) => {
    pagination.page = val
    getUserList()
  }

  // 显示用户详情
  const showDetailDialog = async (row: UserType) => {
    try {
      const response = await UserService.getUserDetail(row.openid)
      console.log('detail response', response)
      currentUser.value = response.data
      detailDialogVisible.value = true
    } catch (error) {
      ElMessage.error('获取用户详情失败')
      console.error('获取用户详情失败:', error)
    }
  }

  // 封禁用户
  const handleBlock = (row: UserType) => {
    ElMessageBox.confirm('确定封禁该用户吗？', '封禁用户', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      try {
        await UserService.updateUser(row.openid, { status: 'blocked' })
        ElMessage.success('用户封禁成功')
        getUserList()
      } catch (error) {
        ElMessage.error('封禁用户失败')
        console.error('封禁用户失败:', error)
      }
    })
  }

  // 解封用户
  const handleUnblock = (row: UserType) => {
    ElMessageBox.confirm('确定解封该用户吗？', '解封用户', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'success'
    }).then(async () => {
      try {
        await UserService.updateUser(row.openid, { status: 'active' })
        ElMessage.success('用户解封成功')
        getUserList()
      } catch (error) {
        ElMessage.error('解封用户失败')
        console.error('解封用户失败:', error)
      }
    })
  }

  // 删除用户
  const handleDelete = (row: UserType) => {
    ElMessageBox.confirm('确定删除该用户吗？删除后用户将无法登录使用。', '删除用户', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      try {
        await UserService.updateUser(row.openid, { status: 'deleted' })
        ElMessage.success('用户删除成功')
        getUserList()
      } catch (error) {
        ElMessage.error('删除用户失败')
        console.error('删除用户失败:', error)
      }
    })
  }

  // 显示VIP设置弹窗
  const showVipDialog = (row: UserType) => {
    currentUser.value = row
    // 重置表单
    Object.assign(vipForm, {
      type: 'monthly',
      activatedAt: Math.floor(Date.now() / 1000),
      expiresAt: null,
      orderId: '',
      isActive: true
    })
    vipDialogVisible.value = true
  }

  // 设置VIP
  const handleSetVip = async () => {
    if (!vipFormRef.value || !currentUser.value) return

    try {
      await vipFormRef.value.validate()
      submitLoading.value = true

      // 如果是终身会员，过期时间设为null
      const vipData: UpdateVipParams = {
        ...vipForm,
        expiresAt: vipForm.type === 'lifetime' ? null : vipForm.expiresAt
      }

      await UserService.updateUserVip(currentUser.value.openid, vipData)
      // 同时更新用户角色为VIP
      await UserService.updateUser(currentUser.value.openid, { role: 'vip' })

      ElMessage.success('VIP设置成功')
      vipDialogVisible.value = false
      getUserList()
    } catch (error) {
      ElMessage.error('VIP设置失败')
      console.error('VIP设置失败:', error)
    } finally {
      submitLoading.value = false
    }
  }

  // 取消VIP
  const handleCancelVip = (row: UserType) => {
    ElMessageBox.confirm('确定取消该用户的VIP权限吗？', '取消VIP', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      try {
        await UserService.updateUser(row.openid, { role: 'normal' })
        ElMessage.success('VIP取消成功')
        getUserList()
      } catch (error) {
        ElMessage.error('取消VIP失败')
        console.error('取消VIP失败:', error)
      }
    })
  }

  // 工具函数
  const formatLocation = (user: UserType): string => {
    const parts = [user.country, user.province, user.city].filter(Boolean)
    return parts.length > 0 ? parts.join(' ') : '-'
  }

  // 生命周期
  onMounted(() => {
    getUserList()
  })
</script>

<style lang="scss" scoped>
  .page-content {
    .user-detail {
      .mt-4 {
        margin-top: 16px;
      }
    }

    .user-info {
      .nickname {
        margin-bottom: 4px;
        font-weight: 500;
        color: var(--el-text-color-primary);
      }

      .phone,
      .openid {
        margin-bottom: 2px;
        font-size: 12px;
        color: var(--el-text-color-secondary);
      }

      .openid {
        line-height: 1.2;
        word-break: break-all;
      }
    }
  }
</style>
